﻿'The MIT License (MIT)
'Copyright(c) 2016 Duff072

'Permission Is hereby granted, free Of charge, to any person obtaining a copy of this software And associated documentation files (the "Software"),
'to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
'And/Or sell copies of the Software, And to permit persons to whom the Software Is furnished to do so, subject to the following conditions:

'The above copyright notice And this permission notice shall be included In all copies Or substantial portions Of the Software.

'THE SOFTWARE Is PROVIDED "AS IS", WITHOUT WARRANTY Of ANY KIND, EXPRESS Or IMPLIED, INCLUDING BUT Not LIMITED To THE WARRANTIES Of MERCHANTABILITY,
'FITNESS For A PARTICULAR PURPOSE And NONINFRINGEMENT. In NO Event SHALL THE AUTHORS Or COPYRIGHT HOLDERS BE LIABLE For ANY CLAIM, DAMAGES Or OTHER LIABILITY,
'WHETHER In AN ACTION Of CONTRACT, TORT Or OTHERWISE, ARISING FROM, OUT Of Or In CONNECTION With THE SOFTWARE Or THE USE Or OTHER DEALINGS In THE SOFTWARE.


'/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
'\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\


Imports System.Net.Mail
'!!!!!!!!!!!!!!!!!!!!!!!!ВАЖНО! Поменять соли и/или алгоритм в функции шифрования пароля!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'!!!!!!!!!!!!!!!!!!!!!!!!ВАЖНО! указать верный пароль в general_settings !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Public Class start
    Function Pass_crypt(ByVal pass As String)
        ' перед сборкой сменить ключ здесь и ниже. Можно юзать :(http://www.emvlab.org/keyshares/)
        Dim wrapper As New MainEnCryptingClass("1234") '+ функция дешифровки
        pass = wrapper.EncryptData(pass)
        Return pass
    End Function
    Function Pass_Decrypt(ByVal pass As String)
        Dim wrapper As New MainEnCryptingClass("1234")
        pass = wrapper.DecryptData(pass)
        Return pass
    End Function
    '**********************************************************************************************************************************
    'ФУНКЦИОНАЛЬНЫЙ КОД СМОТРЕТЬ В МОДУЛЯХ MYFUNCTIONS и MYCODE
    'НАЧАЛО - НАСТРОЙКА ФОРМ, ЭЛЕМЕНТОВ УПРАВЛЕНИЯ, СОБЫТИЙ, БАЗОВЫХ ФУНКЦИЙ (СООБЩЕНИЯ), КРИПТОГРАФИЯ и т.п.
    '**********************************************************************************************************************************
    Private Sub start_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        set_abortcancel.Checked = My.Settings.set_abortcancel
        set_autorun.Checked = My.Settings.set_autorun
        set_min.Checked = My.Settings.set_min
        set_msg.Checked = My.Settings.set_msg
        set_showlogleftclick.Checked = My.Settings.set_showlogleftclick
        set_winstartup.Checked = My.Settings.set_winstartup
        ico_message.Checked = My.Settings.ico_message
        If My.Settings.set_abortcancel = True Then Close_Button.Show() Else Close_Button.Hide()
        If My.Settings.set_min = True Then
            Me.WindowState = FormWindowState.Minimized
            NotifyIcon1.Visible = True
            Me.Hide()
        End If
        'так-же создаем таймер
        Timer1.Interval = My.Settings.timer * 60 * 1000
        If My.Settings.set_autorun = True Then Timer1.Enabled = True

        'Создаем, если нет таблицу адресатов
        If My.Settings.Set_address Is Nothing Then
            My.Settings.Set_address = New DataTable
            My.Settings.Set_address.TableName = "Адресаты"
            My.Settings.Set_address.Columns.Add("Имя рассылки", GetType(String))
            My.Settings.Set_address.Columns.Add("ДТ отправлена", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Присвоен номер", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Начата проверка", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Доп.проверка по стране", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Доп.проверка по стоимости", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Увед. о досмотре", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Акт досмотра", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Проверка окончена", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Выпуск товаров", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("ИД:там.пост", GetType(String))
            My.Settings.Set_address.Columns.Add("ИД:коммент", GetType(String))
            My.Settings.Set_address.Columns.Add("ИД:ком+xls", GetType(String))
            My.Settings.Set_address.Columns.Add("ИД:Имя", GetType(String))
            My.Settings.Set_address.Columns.Add("Emails", GetType(String))
            My.Settings.Set_address.Columns.Add("Резерв 1", GetType(String))
            My.Settings.Set_address.Columns.Add("Резерв 2", GetType(String))
            My.Settings.Set_address.Columns.Add("Резерв 3", GetType(String))
            My.Settings.Set_address.Columns.Add("Резерв 4", GetType(Boolean))
            My.Settings.Set_address.Columns.Add("Резерв 5", GetType(Boolean))
            My.Settings.Set_address.Rows.Add("Новая рассылка", False, False, False, False, False, False, False, False, False, "", "", "", "", "")
            My.Settings.Save()
        End If
        If My.Settings.Set_address.Rows.Count = 0 Then
            My.Settings.Set_address.Rows.Add("Новая рассылка", False, False, False, False, False, False, False, False, False, "", "", "", "", "")
            My.Settings.Save()
        End If
    End Sub
    Private Sub Form_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
        If Me.WindowState = FormWindowState.Minimized Then
            Me.Hide()
            NotifyIcon1.Visible = True
        End If
    End Sub
    Private Sub ОткрытьToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ОткрытьToolStripMenuItem.Click, NotifyIcon1.DoubleClick
        Me.Show()
        Me.WindowState = FormWindowState.Normal
    End Sub
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If My.Settings.set_abortcancel = True And Me.Visible = True Then
            e.Cancel = True
            Me.WindowState = FormWindowState.Minimized
        Else
            If MsgBox("Закрыть программу?", MsgBoxStyle.YesNo, "Вы уверены?") = MsgBoxResult.Yes Then
                NotifyIcon1.Visible = False
                End
                Application.Exit()
            Else
                Me.Show()
                e.Cancel = True
                Me.WindowState = FormWindowState.Normal
            End If
        End If

    End Sub
    Private Sub Close_Button_Click(sender As Object, e As EventArgs) Handles Close_Button.Click, ВыходToolStripMenuItem.Click
        Me.TopMost = True
        Me.Hide() 'скрываем, чтоб отследить, что событие вызвано кнопкой
        Me.Close() 'закрываем форму, см.функцию закрытия формы (Form1_FormClosing)
    End Sub
    Private Sub FAQ_link_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles FAQ_link.LinkClicked
        FAQ.Show()
    End Sub
    Private Sub About_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles About.LinkClicked
        AboutBox1.Show()
    End Sub
    Private Sub NotifyIcon1_Click(ByVal sender As Object, ByVal m As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
        If m.Button = Windows.Forms.MouseButtons.Left Then
            If My.Settings.set_showlogleftclick = True Then
                form_log.Show()
            Else
                message.TopMost = False
                Me.Show()
                Me.WindowState = FormWindowState.Normal

            End If
        End If
    End Sub
    Private Sub notify_message_click() Handles NotifyIcon1.BalloonTipClicked
        If My.Settings.set_showlogleftclick = True Then
            form_log.Show()
        Else
            message.TopMost = False
            Me.Show()
            Me.WindowState = FormWindowState.Normal
        End If
    End Sub
    Private Sub change_setting() Handles set_winstartup.MouseClick, set_showlogleftclick.MouseClick, set_abortcancel.MouseClick, set_autorun.MouseClick, set_min.MouseClick, set_msg.MouseClick, ico_message.MouseClick
        My.Settings.set_abortcancel = set_abortcancel.Checked
        My.Settings.set_autorun = set_autorun.Checked
        My.Settings.set_min = set_min.Checked
        My.Settings.set_msg = set_msg.Checked
        My.Settings.set_showlogleftclick = set_showlogleftclick.Checked
        My.Settings.set_winstartup = set_winstartup.Checked
        My.Settings.ico_message = ico_message.Checked
        If My.Settings.set_abortcancel = True Then Close_Button.Show() Else Close_Button.Hide()
        My.Settings.Save()
        My.Settings.Reload()
    End Sub
    Private Sub AUTORUN(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles set_winstartup.MouseClick
        If set_winstartup.Checked = True Then

            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\", "alta2mail.exe", My.Application.Info.DirectoryPath & "\" & My.Application.Info.AssemblyName & ".exe")
        Else
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\", "alta2mail.exe", "")
        End If
    End Sub
    Private Sub showLOG_Click(sender As Object, e As EventArgs) Handles showLOG.Click, ПоказатьЛогToolStripMenuItem.Click
        form_log.Show()
    End Sub
    Private Sub RUN(sender As Object, e As EventArgs) Handles button_Run.Click
        Timer1.Enabled = True
        work_cancel.Visible = True
        sysmessage("Установлен интервал ", "На " & My.Settings.timer * 60 * 1000 & " мc (" & My.Settings.timer & " мин.)", False)
        Me.WindowState = FormWindowState.Minimized
        Me.Hide()
        sysmessage("Сервис запущен", "", True)
        checkevents() 'Запускаем проверку поданных ДТ
    End Sub
    Private Sub work_cancel_Click(sender As Object, e As EventArgs) Handles work_cancel.Click
        Timer1.Enabled = False
        work_cancel.Visible = False
    End Sub
    Sub sysmessage(ByRef title As String, ByRef text As String, ByRef destination_all As Boolean, Optional ByRef debug_only As Boolean = False)

        Dim temptext As String = Nothing
        If text = "" Then temptext = title Else temptext = title & vbNewLine & vbTab & vbTab & vbTab & text
        If debug_only = False And destination_all = True Then
            If My.Settings.set_msg = True Then ' для большого сообщения
                message.TopMost = True
                If message.Visible Then
                    message.TextBox.AppendText(vbNewLine & Now & " " & vbTab & temptext & vbNewLine)
                Else
                    message.TextBox.Text = Now & " " & vbTab & temptext & vbNewLine
                    message.showmessage()
                End If
            End If
            If My.Settings.ico_message = True Then ' для сообщения иконкой
                'NotifyIcon1.Icon = SystemIcons.Exclamation
                If text = "" Then NotifyIcon1.BalloonTipTitle = "Alta2Mail" Else NotifyIcon1.BalloonTipTitle = title
                If text = "" Then NotifyIcon1.BalloonTipText = title Else NotifyIcon1.BalloonTipText = text
                'NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
                NotifyIcon1.ShowBalloonTip(30000)

            End If
            form_log.log.AppendText(Now & " " & vbTab & temptext & vbNewLine)
        Else ' либо дебаг, либо только для лога
            If debug_only = False Then form_log.log.AppendText(Now & " " & vbTab & temptext & vbNewLine)
        End If
        If My.Settings.debug = True And debug_only = True Then form_log.log.AppendText(Now & " " & vbTab & temptext & vbNewLine)
    End Sub
    Private Sub set_min_checkedChanged(sender As Object, e As EventArgs) Handles set_min.MouseClick
        If set_min.Checked = True Then MsgBox("Так-же имеет смысл поставить первую галочку. В противном случае программа запустится, но не будет следить за сообщениями",, "ВАЖНО!")
    End Sub
    Private Sub showsettingssender_Click(sender As Object, e As EventArgs) Handles showsettingssender.Click
        address.Show()
    End Sub
    Private Sub ico_message_CheckedChanged(sender As Object, e As EventArgs) Handles ico_message.CheckedChanged
        If ico_message.Checked = True Then set_msg.Checked = False
    End Sub
    Private Sub set_msg_CheckedChanged(sender As Object, e As EventArgs) Handles set_msg.CheckedChanged
        If set_msg.Checked = True Then ico_message.Checked = False
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles mailsettshow.Click
        Email.Show()
    End Sub
    Private Sub showgeneralsettings_Click(sender As Object, e As EventArgs) Handles showgeneralsettings.Click
        general_settings.Show()
    End Sub
    Function Send_Mail(ByVal MailTo As String, ByVal MailSubject As String,
ByVal MailText As String, Optional ByVal MailAttachment As String = "", Optional ByVal MailAttachment2 As String = "", Optional ByVal MailAttachment3 As String = "") As Boolean

        Dim smtpserver$, sendusername$, sendpassword$

        smtpserver = My.Settings.smtpname
        sendusername = My.Settings.smtpusername
        sendpassword = Pass_Decrypt(My.Settings.smtppassword)

        If Len(smtpserver) = 0 Or Len(sendusername) = 0 Or Len(sendpassword) = 0 Or Len(My.Settings.smptPORT) = 0 Then
            Send_Mail = False
            sysmessage("ОШИБКА", "SMTP сервер настроен некорректно", False, True)
            Exit Function
        End If

        Try
            Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False
            Smtp_Server.Credentials = New Net.NetworkCredential(String.Format(sendusername, System.Text.Encoding.UTF8), sendpassword)
            Smtp_Server.Port = My.Settings.smptPORT
            Smtp_Server.EnableSsl = My.Settings.smtpSSL
            Smtp_Server.Host = smtpserver

            e_mail = New MailMessage()
            e_mail.From = New MailAddress(My.Settings.smtpsenderemail, My.Settings.smtpnamesender)
            e_mail.To.Add(MailTo)
            e_mail.Subject = MailSubject
            e_mail.IsBodyHtml = True
            e_mail.Body = "<pre>" & MailText & vbNewLine & vbNewLine & "<small>Powered by <a href=""https://alta2mail.codeplex.com/"">Alta2Mail</a>." & vbNewLine & "Email: <a href=""mailto:alta2mail@mail.ru"">alta2mail@mail.ru</a>.</small></pre>"
            If Len(MailAttachment) > 0 Then e_mail.Attachments.Add(New Attachment(MailAttachment))
            If Len(MailAttachment2) > 0 Then e_mail.Attachments.Add(New Attachment(MailAttachment2))
            If Len(MailAttachment3) > 0 Then e_mail.Attachments.Add(New Attachment(MailAttachment3))
            Smtp_Server.Send(e_mail)
            sysmessage("from function: Сообщение отправлено успешно", "", False, True)

            Send_Mail = True

        Catch error_t As Exception
            ' MsgBox(error_t.ToString)
            Send_Mail = False
            sysmessage("При отправке сообщения возникли ошибки ", "" & vbNewLine & error_t.ToString, False, True)
        End Try
    End Function
    '/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    'КОНЕЦ  - НАСТРОЙКА ФОРМ, ЭЛЕМЕНТОВ УПРАВЛЕНИЯ, СОБЫТИЙ и т.п.
    '/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'события по таймеру
        sysmessage("Сработал таймер ", "", False, True)
        sysmessage("Проверка сообщений", "", False)

        'очищяем текстБОКС лога, чтоб не таскать с собой большой груз
        If form_log.log.Lines.Length > 5000 Then
            form_log.log.Text = Mid(form_log.log.Text, form_log.log.TextLength / 2)
            sysmessage("Немножко очистили лог ", "", False, True)
        End If
        cleartempfolder()
        checkevents() 'Запускаем проверку поданных ДТ
    End Sub

End Class